<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Paper;
use App\Http\Models\Question;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//use Illuminate\Support\Facades\Validator;
use Validator;

class QuestionController extends Controller
{
    //显示试卷列表
    public function index(Request $request,Paper $paper){
        $info = $paper->question;//这里要用动态属性 加载question表里的数据(主要查询的是question里的数据，如果用渴求时加载，就变成了 主要取Paper里的数据了)
//        dd($info);
        return view('admin.question.index',compact('paper','info'));
    }

    public function add(Request $request,Paper $paper){
        if($request->isMethod('post')){
            $data = $request->all();
            //试题答案提交过来是一个数组（因为有多选 答案采用二进制算法 1 2 4 8） 多选的话 求和
            if(isset($data['qs_answer'])){
                $data['qs_answer']  = array_sum($data['qs_answer']);
            }else{
                $data['qs_answer'] = 0;
            }

            $data['paper_id']   = $paper->paper_id;

            //数据验证
            $rules = [
                'qs_name'   =>  'required',
                'qs_score'  =>  'required',
                'qs_answer' =>  ['required','regex:/^[1-9]|1[0-5]$/'],
                'qs_type'   =>  'required',
                'option_a'  =>  'required',
                'option_b'  =>  'required',
                'option_c'  =>  'required',
                'option_d'  =>  'required',
                'qs_remark'  =>  'required',

            ];
            $notices = [
              'qs_name.required' => '试题名称不能为空',
              'qs_score.required' => '试题分数不能为空',
              'qs_answer.required' => '试题答案不能为空',
              'qs_type.required' => '试题类型不能为空',
              'option_a.required' => '选项A不能为空',
              'option_b.required' => '选项B不能为空',
              'option_c.required' => '选项C不能为空',
              'option_d.required' => '选项D不能为空',
              'qs_remark.required' => '试题备注不能为空',
            ];
            $validator = Validator::make($data,$rules,$notices);
            if($validator->passes()){
                $res = Question::create($data);
                if($res){
                    return ['success'=>true];
                }else{
                    return ['success'=>false,'errorinfo'=>'试题添加失败'];
                }
            }else{
                $errorinfo = collect($validator->messages())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorinfo];
            }
        }
        return view('admin.question.add',compact('paper'));
    }
}
